package it.asvp.asvp_portal.service.services.impl;

import it.asvp.asvp_portal.asvp_util.enumerative.ReceiverOption;
import it.asvp.asvp_portal.data.dao.MemberAccountDao;
import it.asvp.asvp_portal.data.dao.MemberDao;
import it.asvp.asvp_portal.data.dao.NotificationDao;
import it.asvp.asvp_portal.data.entity.member.Member;
import it.asvp.asvp_portal.data.entity.member.MemberAccount;
import it.asvp.asvp_portal.data.entity.notification.Notification;
import it.asvp.asvp_portal.data.entity.notification.NotificationReceiver;
import it.asvp.asvp_portal.service.services.NotificationService;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

@Service
public class NotificationServiceImpl implements NotificationService {

	@Autowired
	NotificationDao notificationDao;
	@Autowired
	MemberDao memberDao;
	@Autowired
	MemberAccountDao memberAccountDao;
	
	@Transactional
	@Rollback
	public void createNotification(UserDetails userDetails,Notification transientNotification) throws Exception{
		
		MemberAccount persistentCurrentAccount=memberAccountDao.findByLogin(userDetails.getUsername());
		  
		if(persistentCurrentAccount==null){
				throw new Exception("Account errato");
		}
		
		Member persistentMember=persistentCurrentAccount.getMember();
		transientNotification.setMember(persistentMember);
		
		if(ReceiverOption.ALCUNI_SOCI.equals(transientNotification.getReceiverOption())){
			      
			      Set<NotificationReceiver> notificationReceivers=new HashSet<NotificationReceiver>();
			      
		          for(NotificationReceiver nR:transientNotification.getNotificationReceivers()){
		        	  Member receiver=memberDao.findById(nR.getMember().getId());
		        	  if(receiver==null){
		        		   continue;
		        	  }
		        	  notificationReceivers.add(new NotificationReceiver(receiver,transientNotification));
		          }
		          
		          transientNotification.setNotificationReceivers(notificationReceivers);
		 }
		
		 notificationDao.persist(transientNotification);
	}
	
	@Transactional
	@Rollback
	public List<Notification> getAllNotifications(){
		return notificationDao.findAll();
	}
	
	@Transactional
	@Rollback
	public List<Notification> getByStartDate(Date date){
		return notificationDao.findByStartDate(date);
	}
	
}
